package com.njtoyo.taxi.admin.aop;

import com.taxi.util.LoggerUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Author Dell
 * @Date 2018/10/16 11:39
 */
@Aspect
@Component
@Slf4j
public class ControllerLoggerAdvice {

    @Pointcut("within(com.njtoyo.taxi.admin.rest.controller..*) && @annotation(loggerManage)")
    public void pointCut(LoggerManage loggerManage){

    }

    @Before("pointCut(loggerManage)")
    public void addBeforeLogger(JoinPoint joinPoint, LoggerManage loggerManage){

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("Authorization");

        LocalDateTime now = LocalDateTime.now();

        log.info("{} 执行 [ {} ] ,url [ {} ] 开始",now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),loggerManage.description(),request.getServletPath());

        log.info(joinPoint.getSignature().toLongString());

        log.info("user token : [ {} ] ", !StringUtils.hasLength(token) ? "无" : token);

        log.info(LoggerUtil.parseParams(joinPoint.getArgs()));

    }

    @AfterReturning(returning = "rtn",pointcut = "pointCut(loggerManage)")
    public void addAfterReturningLogger(JoinPoint joinPoint, LoggerManage loggerManage, Object rtn) {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        LocalDateTime now = LocalDateTime.now();

        log.info("接口名：{} , 返回值： {} ", joinPoint.getSignature().getName(), rtn == null ? "无" : rtn.toString());

        log.info("{} 执行 [ {} ] ,url [ {} ] 结束",now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),loggerManage.description(),request.getServletPath());

    }

    @AfterThrowing(pointcut = "pointCut(loggerManage)", throwing = "ex")
    public void addAfterThrowingLogger(JoinPoint joinPoint, LoggerManage loggerManage, Exception ex) {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        LocalDateTime now = LocalDateTime.now();

        log.error("{} 执行 [ {} ] ,url [ {} ] 异常 接口名：{}, 异常：{} ，参数：{}",now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),loggerManage.description(),request.getServletPath(),joinPoint.getSignature().getName(), ex.toString(), LoggerUtil.parseParams(joinPoint.getArgs()));

    }

}
